<template>
  <div class="diff-viewer">
    <el-container>
      <!-- Header with controls -->
      <el-header class="diff-header">
        <div class="header-left">
          <h2>差异对比</h2>
          <el-button @click="$router.push('/')" type="primary" plain>
            <el-icon><ArrowLeft /></el-icon>
            返回首页
          </el-button>
        </div>
        
        <div class="header-controls">
          <!-- View mode toggle -->
          <el-radio-group v-model="diffStore.viewMode" @change="diffStore.setViewMode">
            <el-radio-button label="side-by-side">并排对比</el-radio-button>
            <el-radio-button label="inline">内联对比</el-radio-button>
          </el-radio-group>
          
          <!-- Action buttons -->
          <el-button 
            @click="diffStore.swapFiles" 
            :disabled="!diffStore.hasFiles"
            type="info"
            plain
          >
            <el-icon><Switch /></el-icon>
            交换文件
          </el-button>
          
          <el-button 
            @click="diffStore.clearDiff" 
            :disabled="!diffStore.hasFiles"
            type="danger"
            plain
          >
            <el-icon><Delete /></el-icon>
            清除对比
          </el-button>
        </div>
      </el-header>

      <!-- File selection panel -->
      <el-container class="file-selection-panel" v-if="!diffStore.hasFiles">
        <el-main>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="file-selector">
                <template #header>
                  <div class="card-header">
                    <span>选择左侧文件 (旧版本)</span>
                  </div>
                </template>
                <FileSelector 
                  @file-selected="onLeftFileSelected"
                  placeholder="选择要对比的旧版本文件"
                />
              </el-card>
            </el-col>
            
            <el-col :span="12">
              <el-card class="file-selector">
                <template #header>
                  <div class="card-header">
                    <span>选择右侧文件 (新版本)</span>
                  </div>
                </template>
                <FileSelector 
                  @file-selected="onRightFileSelected"
                  placeholder="选择要对比的新版本文件"
                />
              </el-card>
            </el-col>
          </el-row>
        </el-main>
      </el-container>

      <!-- Diff content area -->
      <el-container v-else class="diff-content">
        <!-- Diff stats header -->
        <el-header class="diff-stats" v-if="diffStore.diffStats">
          <div class="stats-info">
            <el-tag type="success" size="large">
              <el-icon><Plus /></el-icon>
              +{{ diffStore.diffStats.additions }}
            </el-tag>
            <el-tag type="danger" size="large">
              <el-icon><Minus /></el-icon>
              -{{ diffStore.diffStats.deletions }}
            </el-tag>
            <el-tag type="warning" size="large">
              <el-icon><Edit /></el-icon>
              ~{{ diffStore.diffStats.modifications }}
            </el-tag>
            <el-tag type="info" size="large">
              总计: {{ diffStore.diffStats.total }} 处变更
            </el-tag>
          </div>
          
          <div class="file-info">
            <span class="file-path">{{ diffStore.leftFile?.path }}</span>
            <el-divider direction="vertical" />
            <span class="version-info">
              {{ formatVersionInfo(diffStore.leftFile) }} ↔ {{ formatVersionInfo(diffStore.rightFile) }}
            </span>
          </div>
        </el-header>

        <!-- Loading state -->
        <el-main v-if="diffStore.isLoading" class="loading-container">
          <el-loading-spinner size="large" />
          <p>正在加载文件内容...</p>
        </el-main>

        <!-- Error state -->
        <el-main v-else-if="diffStore.error" class="error-container">
          <el-alert
            :title="diffStore.error"
            type="error"
            show-icon
            :closable="false"
          />
        </el-main>

        <!-- Diff display -->
        <el-main v-else class="diff-display">
          <!-- Side-by-side view -->
          <div v-if="diffStore.viewMode === 'side-by-side'" class="side-by-side-view">
            <div class="diff-pane left-pane">
              <div class="pane-header">
                <h4>{{ diffStore.leftFile?.path }} ({{ formatVersionInfo(diffStore.leftFile) }})</h4>
              </div>
              <div class="code-container">
                <pre class="code-content" v-html="highlightCode(diffStore.leftFile?.content || '')"></pre>
              </div>
            </div>
            
            <div class="diff-pane right-pane">
              <div class="pane-header">
                <h4>{{ diffStore.rightFile?.path }} ({{ formatVersionInfo(diffStore.rightFile) }})</h4>
              </div>
              <div class="code-container">
                <pre class="code-content" v-html="highlightCode(diffStore.rightFile?.content || '')"></pre>
              </div>
            </div>
          </div>

          <!-- Inline view -->
          <div v-else class="inline-view">
            <div class="diff-html-container" v-html="inlineDiffHtml"></div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, watch } from 'vue'
import { useDiffStore } from '../stores'
import { ArrowLeft, Switch, Delete, Plus, Minus, Edit } from '@element-plus/icons-vue'
import FileSelector from '../components/FileSelector.vue'
import { html as diff2html } from 'diff2html'
import { createPatch } from 'diff'

const diffStore = useDiffStore()

// Handle file selection
const onLeftFileSelected = (selection: { versionId: string, fileId: string, path: string }) => {
  diffStore.setLeftFile(selection.versionId, selection.fileId, selection.path)
}

const onRightFileSelected = (selection: { versionId: string, fileId: string, path: string }) => {
  diffStore.setRightFile(selection.versionId, selection.fileId, selection.path)
}

// Format version info for display
const formatVersionInfo = (file: any) => {
  if (!file) return ''
  return `版本 ${file.versionId.substring(0, 8)}`
}

// Generate inline diff HTML using diff2html
const inlineDiffHtml = computed(() => {
  if (!diffStore.leftFile || !diffStore.rightFile) return ''
  
  try {
    const diff = createPatch(
      diffStore.leftFile.path,
      diffStore.leftFile.content,
      diffStore.rightFile.content,
      formatVersionInfo(diffStore.leftFile),
      formatVersionInfo(diffStore.rightFile)
    )
    
    return diff2html(diff, {
      drawFileList: false,
      matching: 'lines',
      outputFormat: 'line-by-line'
    })
  } catch (error) {
    console.error('Error generating diff:', error)
    return '<div class="error">生成差异对比时出错</div>'
  }
})

// Simple syntax highlighting for side-by-side view
const highlightCode = (content: string) => {
  if (!content) return ''
  
  // Basic syntax highlighting (this is simplified)
  return content
    .split('\n')
    .map((line, index) => {
      const lineNumber = index + 1
      const escapedLine = line
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
      
      return `<div class="code-line" data-line="${lineNumber}">
        <span class="line-number">${lineNumber}</span>
        <span class="line-content">${escapedLine}</span>
      </div>`
    })
    .join('')
}

// Initialize component
onMounted(() => {
  // Component initialization logic can be added here
})

// Watch for comparison completion
watch(() => diffStore.hasDiff, (hasDiff) => {
  if (hasDiff && !diffStore.isComparable) {
    // Show warning if files are not comparable
    console.warn('Selected files are not comparable')
  }
})
</script>

<style scoped>
.diff-viewer {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.diff-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: var(--el-color-primary-light-9);
  border-bottom: 1px solid var(--el-border-color);
  padding: 0 20px;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-selection-panel {
  flex: 1;
  background-color: var(--el-bg-color-page);
}

.file-selector {
  height: 400px;
}

.card-header {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.diff-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.diff-stats {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  padding: 12px 20px;
  height: auto;
  min-height: 50px;
}

.stats-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.file-path {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.version-info {
  font-family: monospace;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.diff-display {
  flex: 1;
  padding: 0;
  overflow: hidden;
}

.side-by-side-view {
  display: flex;
  height: 100%;
}

.diff-pane {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--el-border-color);
}

.diff-pane:last-child {
  border-right: none;
}

.pane-header {
  padding: 12px 16px;
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
}

.pane-header h4 {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.code-container {
  flex: 1;
  overflow: auto;
  background-color: var(--el-bg-color-page);
}

.code-content {
  margin: 0;
  padding: 0;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre;
}

.code-line {
  display: flex;
  min-height: 20px;
  border-bottom: 1px solid transparent;
}

.code-line:hover {
  background-color: var(--el-color-primary-light-9);
}

.line-number {
  display: inline-block;
  width: 50px;
  padding: 0 8px;
  text-align: right;
  color: var(--el-text-color-placeholder);
  background-color: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color);
  user-select: none;
}

.line-content {
  flex: 1;
  padding: 0 12px;
  white-space: pre;
}

.inline-view {
  height: 100%;
  overflow: auto;
}

.diff-html-container {
  height: 100%;
}

/* Diff2Html styling overrides */
:deep(.d2h-wrapper) {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
}

:deep(.d2h-file-header) {
  background-color: var(--el-bg-color);
  border-color: var(--el-border-color);
}

:deep(.d2h-code-line-add) {
  background-color: var(--el-color-success-light-9);
}

:deep(.d2h-code-line-del) {
  background-color: var(--el-color-danger-light-9);
}

:deep(.d2h-code-line-cxt) {
  background-color: var(--el-bg-color-page);
}

:deep(.d2h-ins) {
  background-color: var(--el-color-success-light-7);
}

:deep(.d2h-del) {
  background-color: var(--el-color-danger-light-7);
}
</style>